package com.yueya.im.node.handler.impl;

import com.yueya.im.common.api.BusinessInfoProvider;
import com.yueya.im.dao.tables.pojos.FriendDO;
import com.yueya.im.dao.tables.pojos.UserGroupDO;
import com.yueya.im.node.util.CacheUtil;
import com.yueya.im.node.util.RedisUtil;
import com.yueya.im.service.FriendService;
import com.yueya.im.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class ImInfoProvider implements BusinessInfoProvider {

    @Autowired
    private GroupService groupService;

    @Autowired
    private FriendService friendService;

    @Override
    public List<String> mermber(String groupId) {
        List<String> mers;
        if("1000000001".equals(groupId)){
            return CacheUtil.getUserList();
        }
        if(RedisUtil.getRedisUtil().exists(groupId)){
            mers = RedisUtil.getRedisUtil().lrange(groupId,0,-1);
        }else{
            List<UserGroupDO> userGroupDOList = groupService.fetchMembers(groupId);
            mers = userGroupDOList.stream().map(r ->String.valueOf(r.getUserId())).collect(Collectors.toList());
            RedisUtil.getRedisUtil().rpush(groupId,mers.toArray(new String[mers.size()]));
        }
        return mers;
    }

    @Override
    public List<String> friends(String userId) {
        FriendDO friendDO = new FriendDO();
        friendDO.setMyId(Long.valueOf(userId));
        return friendService.listFriend(friendDO)
                .stream()
                .map(r->{return String.valueOf(r.getFriendId());})
                .collect(Collectors.toList());
    }
}
